package com.example.socket.client;

import com.example.socket.core.Command;
import com.example.socket.core.Message;
import com.example.socket.core.Request;
import com.example.socket.core.Session;
import com.example.socket.handler.CommandInfo;
import com.example.socket.handler.DispatcherSupport;
import com.example.socket.handler.Processor;

/**
 * @author frank
 * 客户端指令分发器
 */
@SuppressWarnings({"rawtypes", "unchecked"})
public class ClientDispatcher extends DispatcherSupport {

    @Override
    public void receive(Message message, Session session) {
        super.receive(message, session);

        Command command = message.getCommand();
        CommandInfo info = getCommand(command);
        if (info != null && info.hasProcessor() && !message.isResponse()) {
            Request<?> request = decodeRequest(message);
            process(request, session);
        }
    }

    /**
     * 处理请求并返回消息体(不做参数验证)
     * @param request 请求对象
     * @param session 请求会话
     * @return [0]:信息体,[1]:附加信息
     */
    private void process(final Request request, final Session session) {
        // 获取请求定义
        final Command command = request.getCommand();
        Processor<?, ?> processor = getProcessor(command);
        if (logger.isDebugEnabled()) {
            logger.debug("收到指令[{}]请求, 处理器[{}]", command, processor);
        }
        // 处理请求
        processor.process(request, session, null);
    }

}
